import React, {Component} from "react";
import {
  Table,
  Badge,
  Card,
  Input,
  Select,
  Modal,
  Tooltip,
  Button,
  Icon,
  Transfer
} from 'antd';
import {connect} from "dva";
import EditForm from '../../components/AutoForm/EditForm';
const {Option} = Select;
const {TextArea} = Input;
const confirm = Modal.confirm;
const statusMap = ['processing', 'warning'];
const status = ['使用中', '锁定'];

@connect(({resource, resourceType, loading}) => ({
  tableLoading: loading.effects['resource/page'],
  modalInsertLoading: loading.effects['resource/insert'],
  modalUpdateLoading: loading.effects['resource/update'],
  modalTransferLoading: loading.effects['resource/saveMenuElems'],
  searchForm: resource.searchForm,
  modalForm: resource.modalForm,
  addForm: resource.addForm,
  modalVisible: resource.modalVisible,
  tableData: resource.list,
  selection: resource.selection,
  optFlag: resource.optFlag,
  defaultExpandAllRows: resource.defaultExpandAllRows,
  resTypeOptions: resourceType.resTypeOptions,
  transferVisible: resource.transferVisible,
  transferTitle: resource.transferTitle,
  elemsData: resource.elemsData,
  activeMenuId: resource.activeMenuId,
  elemsTargetKeys: resource.elemsTargetKeys
}))
export default class List extends Component {

  columns = [
    {
      title: '名称',
      width: 240,
      dataIndex: 'name',
    },
    {
      title: '编码',
      width: 280,
      dataIndex: 'code',
    },
    {
      title: '路径',
      width: 220,
      dataIndex: 'path',
    },
    {
      title: '图标',
      width: 160,
      dataIndex: 'icon',
    },
    {
      title: '模块',
      width: 160,
      dataIndex: 'model'
    },
    {
      title: '描述',
      width: 360,
      dataIndex: 'descr'
    },
    {
      title: '锁定/使用',
      width: 120,
      dataIndex: 'isLock',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]}/>;
      },
    },
    {
      title: '操作',
      width: 150,
      align: "center",
      fixed: 'right',
      render: (text, record, index) => {
        return(
          <div>
            {record.type === 'MENU' ? '' :<Tooltip title="添加"><Button shape="circle" size="small" onClick={() => this.handleModalVisible('add',record)}><Icon type="plus"/></Button></Tooltip>}
            <Tooltip title="删除"><Button shape="circle" size="small" onClick={() => this.handleDel(record)}><Icon type="minus"/></Button></Tooltip>
            <Tooltip title="编辑"><Button shape="circle" size="small" onClick={() => this.handleModalVisible('edit',record)}><Icon type="edit"/></Button></Tooltip>
            {record.type === 'MENU' ? <Tooltip title="关联元素"><Button shape="circle" size="small" onClick={() => this.handleElemsTransfer('edit',record)}><Icon type="radius-setting"/></Button> </Tooltip> : ''}
          </div>
        )
      },
    }
  ];

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'resource/page'
    });
    dispatch({
      type: 'resourceType/getOptions'
    });
  }

  handleSearch = () => {
    const {dispatch, searchForm} = this.props;
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const param = {
      ...searchValue,
    };
    dispatch({
      type: 'resource/page',
      payload: param
    })
  }

  handleModalVisible = (opt, record) => {
    const {dispatch, modalVisible, addForm} = this.props;
    let payload = {modalVisible: !modalVisible};
    let modalForm = {};
    if ('edit' === opt) {
      Object.keys(record).map((key) => {
        modalForm[key] = {value: record[key]}
      })
    } else if ("add" === opt) {
      Object.keys(addForm).map((key) => {
        modalForm[key] = {value: addForm[key]}
      })
      modalForm['parentCode'] = {value: record.code};
      modalForm['parentId'] = {value: record.id};
    }

    if (!modalVisible) {
      payload.optFlag = opt;
      payload.modalForm = modalForm;
    }
    dispatch({
      type: 'resource/handleModalVisible',
      payload: payload
    })
  }

  handleModalChange = (fields) => {
    const {dispatch, optFlag, addForm} = this.props;
    const payload = {fields: fields, optFlag: optFlag, addForm: addForm};
    dispatch({
      type: 'resource/handleModalChange',
      payload: payload
    })
  }


  handleOk = (fields) => {

    const {dispatch, optFlag, searchForm, pagination} = this.props;
    const payload = {
      fields: fields,
      searchForm: searchForm,
      pagination: pagination
    }
    if (optFlag === 'add') {
      dispatch({
        type: 'resource/insert',
        payload: payload
      })
    } else if (optFlag === 'edit') {
      dispatch({
        type: 'resource/update',
        payload: payload
      })
    }

  }

  handleDel = (record) => {
    const {dispatch } = this.props;
    const payload = {
      fields: record,
    }
    confirm({
      title: '是否确认删除此资源吗?',
      content: `编码：${record.code}; 名称：${record.name}`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'resource/del',
          payload: payload,
        });
      },
    });
  }

  filterOption = (inputValue, option) => option.description.toUpperCase().indexOf(inputValue.toUpperCase()) > -1;

  handleTransferVisible = () => {
    const {dispatch,transferVisible} = this.props;
    dispatch({
      type: 'resource/handleTransferVisible',
      payload: !transferVisible
    })
  }

  handleTransferChange = targetKeys => {
    const {dispatch} = this.props;
    dispatch({
      type: 'resource/handleTransferChange',
      payload: targetKeys
    })
  }

  handleTransferOk = () => {
    const {dispatch, activeMenuId, elemsTargetKeys} = this.props;
    this.handleTransferVisible();
    let menuElems = {menuId: activeMenuId, elemIds: elemsTargetKeys}
    dispatch({
      type: 'resource/saveMenuElems',
      payload: menuElems
    })
  }

  handleElemsTransfer = (text, record, index) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'resource/getTransfer',
      payload: {menuId: record.id}
    }).then(() => {
      this.handleTransferVisible();
    })
    dispatch({
      type: 'resource/handleTransferTitleChange',
      payload: `分配元素(编码：${record.code}，名称：${record.name})`
    })
    dispatch({
      type: 'resource/handleActiveMenuChange',
      payload: record.id
    })
  };
  render() {
    const {
      tableLoading,
      modalInsertLoading,
      modalUpdateLoading,
      modalTransferLoading,
      defaultExpandAllRows,
      tableData,
      modalVisible,
      modalForm,
      optFlag,
      resTypeOptions,
      transferVisible,
      transferTitle,
      elemsData,
      elemsTargetKeys
    } = this.props;
    const options = resTypeOptions.map(d => <Option key={d.value} value={d.value}>{d.label}</Option>);
    const EditRows = [
      {
        cols: [
          {
            label: '父级编码',
            name: 'parentCode',
            md: 18,
            component: <Input disabled={true} placeholder="请输入编码"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '名称',
            name: 'name',
            md: 18,
            rules: [{required: true, message: '请输入名称！'}],
            component: <Input placeholder="请输入名称"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '编码',
            name: 'code',
            md: 18,
            rules: [{required: true, message: '请输入至少四个字符！', min: 4}],
            component: <Input placeholder="请输入编码"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '类型',
            name: 'type',
            md: 18,
            rules: [{required: true, message: '请选择类型'}],
            component: <Select placeholder={"请选择类型"}>{options}</Select>
          }
        ]
      },
      {
        cols: [
          {
            label: '路径',
            name: 'path',
            md: 18,
            component: <Input placeholder="请输入路径"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '图标',
            name: 'icon',
            md: 18,
            component: <Input placeholder="请输入图标"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '模块',
            name: 'model',
            md: 18,
            component: <Input placeholder="请输入模块"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '描述',
            name: 'descr',
            md: 18,
            component: <TextArea placeholder="请输入描述"/>
          },
          {
            name: 'id',
            component: <Input type="hidden"/>
          },
          {
            name: 'parentId',
            component: <Input type="hidden"/>
          }
        ]
      }
    ];

    return (
      <Card bodyStyle={{padding: 0}}>
        <Table
          pagination={false}
          columns={this.columns}
          loading={tableLoading}
          dataSource={tableData}
          defaultExpandAllRows={defaultExpandAllRows}
          rowKey={record => record.id}
          scroll={{x: 'max-content'}}
          size="small"
        />
        <EditForm
          rows={EditRows}
          fieldValue={modalForm}
          onFieldsChange={this.handleModalChange}
          optFlag={optFlag}
          visible={modalVisible}
          onOk={this.handleOk}
          onCancel={this.handleModalVisible}
          confirmLoading={modalInsertLoading || modalUpdateLoading}
        />
        <Modal
          width= "660px"
          visible={transferVisible}
          title={transferTitle}
          okText="确定"
          cancelText="取消"
          onCancel={this.handleTransferVisible}
          onOk={this.handleTransferOk}
          confirmLoading={modalTransferLoading}
        >
          <Transfer
            dataSource={elemsData}
            showSearch
            listStyle={{height: "600px", width: "240px"}}
            filterOption={this.filterOption}
            targetKeys={elemsTargetKeys}
            onChange={this.handleTransferChange}
            render={item => item.title}
          />
        </Modal>
      </Card>
    )
  }
}
